//
//  InformationViewController.m
//  Tiger
//
//  Created by King on 11-9-9.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "InformationViewController.h"
#import "NewsDetailsViewController.h"
#import <QuartzCore/QuartzCore.h>

#define kCustomRowCount     5

#define kNewsID				@"newsID"
#define kTitle				@"title"

#define TagWhiteLabel 0x100
#define TagWhiteLabelDown 0x101

@implementation InformationViewController
@synthesize tableView = tableView_;
@synthesize myImageView;
@synthesize parsedDataArray;
@synthesize dict;



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib
- (void)viewDidLoad {
    [super viewDidLoad];
    
    myImageView = [[NSMutableArray alloc] init];
    if([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)] ) {
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"top.png"] forBarMetrics: UIBarMetricsDefault];
        self.navigationController.navigationBar.clipsToBounds = YES;
        
    }
	[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"top.png"]];
	self.navigationController.navigationBar.tintColor =  [UIColor colorWithRed:33.0/255 green:32.0/255 blue:32.0/255 alpha:1.0];
	self.parsedDataArray = [NSMutableArray arrayWithCapacity:50];
	[self sendRequestPayInfo];
	
    p_WhiteButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    [p_WhiteButton addTarget:self action:@selector(PressedToDetail:) forControlEvents:UIControlEventTouchUpInside];
    [p_WhiteButton retain];
    p_WhiteButton.frame =CGRectMake(0, 204, 320, 44);
    p_WhiteButton.backgroundColor =[UIColor clearColor];
    p_WhiteButton.layer.shadowOffset =CGSizeMake(3, 3);
    p_WhiteButton.layer.shadowColor =[UIColor grayColor].CGColor;
    CAGradientLayer* tGradlayer =[CAGradientLayer layer];
    tGradlayer.colors = [NSArray arrayWithObjects:(id)[UIColor whiteColor].CGColor,
                         (id)[UIColor lightGrayColor].CGColor ,nil];
    tGradlayer.frame =CGRectMake(0, 0, 320, 44);
    [p_WhiteButton.layer addSublayer:tGradlayer];
    
    UIImageView* tArrow = [[UIImageView alloc] initWithFrame:CGRectMake(300, 14, 12, 12)];
    UIImage* tImg =[UIImage imageNamed:@"arrowin.png"];
    [tArrow setImage:tImg];
    [p_WhiteButton addSubview:tArrow];
    [tArrow release];
    UILabel* tShowDetailLabel =[[UILabel alloc] initWithFrame:CGRectMake(10, 12, 270, 20)];
    tShowDetailLabel.backgroundColor =[UIColor clearColor];
    tShowDetailLabel.font = [UIFont boldSystemFontOfSize:18.f];
    tShowDetailLabel.tag =TagWhiteLabel;
    [p_WhiteButton addSubview:tShowDetailLabel];
    [tShowDetailLabel release];
    [self.view addSubview:p_WhiteButton];
    
    p_TableViewBG =[[UIView alloc] initWithFrame:CGRectMake(0, 244, 320, 200)];
    CAGradientLayer* tBGGradlayer =[CAGradientLayer layer];
    tBGGradlayer.colors = [NSArray arrayWithObjects:(id)[UIColor colorWithRed:50/255.f green:50/255.f blue:50/255.f alpha:1.0f].CGColor,
                         (id)[UIColor blackColor].CGColor ,nil];
    tBGGradlayer.frame =CGRectMake(0, 0, 320, 200);
    [p_TableViewBG.layer addSublayer:tBGGradlayer];
    
    
    tableView_.separatorColor = [UIColor grayColor];
    p_IsPushToVC = NO;
}

-(void) PressedToDetail:(NSInteger)sendertag{
	if (sendertag<[parsedDataArray count]) {
		
//		[self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:sender.tag inSection:0]
//									animated:YES
//							  scrollPosition:UITableViewScrollPositionTop];
		
		
		
		dict = [parsedDataArray objectAtIndex:sendertag];
//		NSTimer *pTime;
		[self TimeCountDown];
//		pTime = [[NSTimer scheduledTimerWithTimeInterval:0.3
//												  target:self
//												selector:@selector(TimeCountDown:)
//												userInfo:nil
//												 repeats:NO] retain];
//		[pTime release];
		

	}
}


-(void)sendRequestPayInfo
{
	NSURL* serverURL = [NSURL URLWithString:URL_NewsList];
	ASIFormDataRequest* request = [ASIFormDataRequest requestWithURL:serverURL];
	request.tag = -1;
	[request setValidatesSecureCertificate:NO];
	[request setDelegate:self];
	[request startAsynchronous];
}

#pragma mark ASIHTTPRequestDelegate methods
- (void)requestStarted:(ASIHTTPRequest *)request
{
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}


- (void)requestFinished:(ASIHTTPRequest *)request;
{
	NSData *responseData = [request responseData];
	NSString *responseStr = [[[NSString alloc] initWithData:responseData encoding: NSUTF8StringEncoding] autorelease];
	if (request.tag < 0) 
	{
		NSDictionary *tdict = [responseStr JSONValue];
		self.parsedDataArray = [tdict objectForKey:@"items"];
        
        [myImageView removeAllObjects];
        int index =0;
        for (NSDictionary* infodic in parsedDataArray) {
            AsyncImageView* tImgs =[[AsyncImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 204)];
            tImgs._numStateRequested = need_Request;
            tImgs._imageRequestURL = [infodic objectForKey:@"picUrl"];
            NSLog(@"%@",tImgs._imageRequestURL);
            tImgs.m_BoolSetImage = YES;
            [myImageView addObject:tImgs];
            if (index==0) {
                [tImgs customLoadImageFromURL];
                [self.view addSubview:tImgs];
            }
            [tImgs release];  
            index++;
        }
        
        
        UILabel* tInLabel =(UILabel*)[p_WhiteButton viewWithTag:TagWhiteLabel];
        NSDictionary *dictlabel = [parsedDataArray objectAtIndex:0];
		tInLabel.text = [dictlabel objectForKey:kTitle];
		[self.tableView reloadData];
	}
	else {
		NSLog(@"recved bad data !");
	}
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"无可用的网络连接" delegate:self 
										   cancelButtonTitle:nil otherButtonTitles:nil] autorelease];
	[alert addButtonWithTitle:@"确定"];
	[alert show];
	
}

#pragma mark Table view methods
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//	return 60.0;
//}

// Customize the number of rows in the table view. UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
	int count = [parsedDataArray count];
    if (count == 0)
	{
        return kCustomRowCount;
    }
    return count;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    [tableView setBackgroundView:p_TableViewBG];
	static NSString* CellIdentifier = @"Cellidentifier";
	static NSString *PlaceholderCellIdentifier = @"PlaceholderCell";	
	int nodeCount = [self.parsedDataArray count];
	//NSLog(@"nodeCount = %d", nodeCount);
	if (nodeCount == 0 && indexPath.row == 0)
	{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:PlaceholderCellIdentifier];
        if (cell == nil)
		{
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
										   reuseIdentifier:PlaceholderCellIdentifier] autorelease];   
            cell.detailTextLabel.textAlignment = UITextAlignmentCenter;
			cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
		cell.detailTextLabel.text = @"数据加载中，请稍后…";
		
		return cell;
    }

	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle 
									   reuseIdentifier:CellIdentifier] autorelease];
		
    }
	if (nodeCount > 0)
	{
		int index = indexPath.row;
		NSDictionary *tdict = [parsedDataArray objectAtIndex:index];
		
		cell.textLabel.text = [tdict objectForKey:kTitle];

		cell.textLabel.font = [UIFont boldSystemFontOfSize:15];
		cell.textLabel.textColor = [UIColor lightGrayColor];

		cell.indentationLevel = 0;
		cell.indentationWidth = 0;
		
		//cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	}
	cell.selectionStyle = UITableViewCellSelectionStyleNone;
	return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (p_IsPushToVC) {
        return;
    }
    if (indexPath.row == p_LastShowImgIndex) {
        CGPoint aOffset =CGPointMake(0,44*(indexPath.row+1));
        
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        [UIView setAnimationDuration:0.5f];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDidStopSelector:@selector(removeLastView)];
        tableView.contentOffset =aOffset;
        [UIView commitAnimations];
        return;
    }
    p_IsPushToVC =YES;
    UILabel* tShowDetailLabel =[[UILabel alloc] initWithFrame:CGRectMake(10, 56, 270, 20)];
    tShowDetailLabel.backgroundColor =[UIColor clearColor];
    tShowDetailLabel.font = [UIFont boldSystemFontOfSize:18.f];
    tShowDetailLabel.tag =TagWhiteLabelDown;
    p_WhiteButton.clipsToBounds =YES;
    [p_WhiteButton addSubview:tShowDetailLabel];
    
    UILabel* tInLabel =(UILabel*)[p_WhiteButton viewWithTag:TagWhiteLabel];
    
    NSDictionary *dictlabel = [parsedDataArray objectAtIndex:indexPath.row];
    tShowDetailLabel.text = [dictlabel objectForKey:kTitle];
    p_WhiteButton.tag =indexPath.row;
    
    AsyncImageView* tShow =[myImageView objectAtIndex:indexPath.row];
    if (tShow._numStateRequested == need_Request) {
        [tShow customLoadImageFromURL];
    }
    tShow.frame =CGRectMake(0, 204, 320, 204);
    
    //[self.view addSubview:tShow];
    [self.view insertSubview:tShow atIndex:1];
    AsyncImageView* tLastShow =[myImageView objectAtIndex:p_LastShowImgIndex];
    p_NowShowIndex = indexPath.row;
    
//    [tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
    CGPoint aOffset =CGPointMake(0,44*(indexPath.row+1));
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.5f];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(removeLastView)];
    tShow.frame =CGRectMake(0, 0, 320, 204);
    tLastShow.frame =CGRectMake(0, -204, 320, 204);
    tInLabel.frame =CGRectMake(10, -32, 270, 20);
    tShowDetailLabel.frame =CGRectMake(10, 12, 270, 20);
    tableView.contentOffset =aOffset;
    [UIView commitAnimations];
}

-(void)removeLastView{
    AsyncImageView* tLastShow =[myImageView objectAtIndex:p_LastShowImgIndex];
    [tLastShow removeFromSuperview];
    tLastShow.frame =CGRectMake(0, 0, 320, 204);
    p_LastShowImgIndex =p_NowShowIndex;
    p_NowShowIndex = 0;
    
    UILabel* tInLabel =(UILabel*)[p_WhiteButton viewWithTag:TagWhiteLabel];
    [tInLabel removeFromSuperview];
    UILabel* tDownLabel =(UILabel*)[p_WhiteButton viewWithTag:TagWhiteLabelDown];
    tDownLabel.tag = TagWhiteLabel;
    
    [self PressedToDetail:p_LastShowImgIndex];
    
}

- (void)TimeCountDown{
	NewsDetailsViewController *viewController = [[NewsDetailsViewController alloc] initWithNibName:@"NewsDetailsViewController" bundle:nil];
	viewController.hidesBottomBarWhenPushed = YES;
	
	NSString *st_newsID = [dict objectForKey:kNewsID];
	viewController.newsID = [st_newsID intValue];
	
	UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
								   initWithTitle:@"刀具百科" 
								   style:UIBarButtonItemStylePlain 
								   target:self
								   action:nil];
	self.navigationItem.backBarButtonItem = backButton;
	//导航自带的动画
	[self.navigationController pushViewController:viewController animated:YES];
	[viewController release];
    p_IsPushToVC =NO;
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
	//self.myImageView = nil;
}


- (void)dealloc {
    [p_TableViewBG release];
    [p_WhiteButton release];
    [super dealloc];
	[tableView_ release];
	[myImageView release];
	[parsedDataArray release];
	[dict release];
}


@end
